package com.weilele.mvvm.view

import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.LiveData
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager.widget.ViewPager
import androidx.viewpager2.widget.ViewPager2
import com.weilele.mvvm.base.helper.StatusLiveData
import com.weilele.mvvm.base.helper.StatusValue
import com.weilele.mvvm.base.helper.createStatusLiveData
import com.weilele.mvvm.base.helper.success
import com.weilele.mvvm.utils.safeGet
import java.util.*

class BottomNavigateView : RecyclerView {
    abstract class BottomNavigateAdapter<Data>(val datas: MutableList<Data>) {
        abstract fun getItemView(parent: ViewGroup, lp: ViewGroup.LayoutParams): View

        abstract fun onBindItemView(itemView: View, data: Data, position: Int, isSelect: Boolean)
    }

    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(
        context,
        attrs,
        defStyle
    )

    init {
        setHasFixedSize(true)
        itemAnimator = null
        layoutManager =
            object : LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false) {
                override fun canScrollHorizontally(): Boolean {
                    return false
                }

                override fun canScrollVertically(): Boolean {
                    return false
                }
            }
    }

    override fun setLayoutParams(params: ViewGroup.LayoutParams?) {
        super.setLayoutParams(params)
    }

    fun <Data> setBottomNavigateAdapter(adapter: BottomNavigateAdapter<Data>?) {
        if (adapter == null) {
            this.adapter = null
        } else {
            post {
                this.adapter = RcvAdapter(adapter)
            }
        }
    }

    /**
     * 当前界面索引，可以监听设置
     */
    val currentIndexData: LiveData<StatusValue<Int>> = createStatusLiveData()

    /**
     * 设置当前界面位置
     */
    fun setCurrentItem(index: Int, smoothScroll: Boolean = true) {
        viewPager?.setCurrentItem(index, smoothScroll)
        viewPager2?.setCurrentItem(index, smoothScroll)
    }

    private var viewPager: ViewPager? = null
    private var viewPager2: ViewPager2? = null
    private var smoothScroll = false
    fun setupWithViewPager(view: ViewPager, smoothScroll: Boolean = this.smoothScroll) {
        viewPager = view
        this.smoothScroll = smoothScroll
        view.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrollStateChanged(state: Int) {

            }

            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
            }

            override fun onPageSelected(position: Int) {
                adapter.safeGet<RcvAdapter<*>>()?.notifyPositionChange(position)
            }
        })
        adapter.safeGet<RcvAdapter<*>>()?.notifyPositionChange(view.currentItem)
    }

    fun setupWithViewPager(view: ViewPager2, smoothScroll: Boolean = this.smoothScroll) {
        viewPager2 = view
        this.smoothScroll = smoothScroll
        view.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageScrollStateChanged(state: Int) {

            }

            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
            }

            override fun onPageSelected(position: Int) {
                adapter.safeGet<RcvAdapter<*>>()?.notifyPositionChange(position)
            }
        })
        adapter.safeGet<RcvAdapter<*>>()?.notifyPositionChange(view.currentItem)
    }

    private inner class RcvAdapter<Data>(private val adapter: BottomNavigateAdapter<Data>) :
        RecyclerView.Adapter<RcvHolder>() {
        private val childWidth = width / adapter.datas.count()
        private var select = 0
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RcvHolder {
            val lp = ViewGroup.LayoutParams(childWidth, ViewGroup.LayoutParams.MATCH_PARENT)
            val itemView = adapter.getItemView(parent, lp)
            itemView.layoutParams = lp
            val rcvHolder = RcvHolder(itemView)
            itemView.setOnClickListener {
                val newSelectPosition = rcvHolder.layoutPosition
                if (newSelectPosition != select) {
                    if (viewPager == null && viewPager2 == null) {
                        notifyPositionChange(newSelectPosition)
                    } else {
                        setCurrentItem(newSelectPosition, smoothScroll)
                    }
                }
            }
            return rcvHolder
        }

        fun notifyPositionChange(newSelectPosition: Int) {
            if (select != newSelectPosition) {
                val old = select
                select = newSelectPosition
                notifyItemChanged(newSelectPosition)
                notifyItemChanged(old)
                currentIndexData.success(newSelectPosition)
            }
        }

        override fun getItemCount(): Int = adapter.datas.count()

        override fun onBindViewHolder(holder: RcvHolder, position: Int) {
            val isSelect = select == position
            holder.itemView.isSelected = isSelected
            adapter.onBindItemView(holder.itemView, adapter.datas[position], position, isSelect)
        }
    }

    private inner class RcvHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
}